package reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Scanner;

/**
 * 通过反射机制调用无参方法
 */
public class ReflectDemo4 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Scanner sc = new Scanner(System.in );
        System.out.println("请输入一个类名：");
        String className = sc.nextLine();
        System.out.println("请输入一个方法名：");
        String methodName = sc.nextLine();

        Class cls = Class.forName(className);  //获取一个类对象
        Constructor c  = cls.getConstructor(String.class);  //获取类的构造方法
        Object obj = c.newInstance("张三");  //new对象-----new Person("张三")；
        Method method = cls.getMethod(methodName);  //获取类的方法对象
        method.invoke(obj);  //调用方法-----obj.sayHi();


    }
}
